package com.ccc.boot.monitor.controller;

import com.ccc.boot.constant.CommonConstant;
import com.ccc.boot.monitor.pojo.RedisVO;
import com.ccc.boot.monitor.service.CacheService;
import com.ccc.boot.response.ResponseCode;
import com.ccc.boot.response.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * redis缓存管理
 *
 * @author superC
 * @version 2.0.0
 * @date 2022/4/24
 */

@RestController
@RequestMapping(CommonConstant.MONITOR_URI_PREFIX + "/cache")
public class CacheController {

    @Autowired
    private CacheService cacheService;


    /**
     * 删除指定key
     */
    @DeleteMapping("/{key}")
    public ResponseResult delete(@PathVariable String key) {
        // 业务逻辑
        boolean deleted = cacheService.delete(key);
        if (deleted) {
            return ResponseResult.success(ResponseCode.DATA_DELETE_SUCCESS);
        }
        return ResponseResult.failure(ResponseCode.DATA_DELETE_FAILURE);
    }

    /**
     * 删除所有匹配指定前缀的key
     */
    @DeleteMapping("/pre/{prefix}")
    public ResponseResult deletePrefix(@PathVariable String prefix) {
        // 业务逻辑
        boolean deleted = cacheService.deleteByPrefix(prefix);
        if (deleted) {
            return ResponseResult.success(ResponseCode.DATA_DELETE_SUCCESS);
        }
        return ResponseResult.failure(ResponseCode.DATA_DELETE_FAILURE);
    }

    /**
     * 清空Redis缓存
     */
    @DeleteMapping("/deleteAll")
    public ResponseResult deleteAll() {
        // 业务逻辑
        boolean deleted = cacheService.flushRedis();
        if (deleted) {
            return ResponseResult.success("清空Redis缓存成功");
        }
        return ResponseResult.failure("清空Redis缓存失败");
    }

    /**
     * 查询Redis缓存
     */
    @GetMapping("/getList")
    public ResponseResult getList() {
        List<RedisVO> list = cacheService.getList();
        return ResponseResult.success("查询成功", list);
    }


}
